// api/device.js获取设备数据
import CommonConstant from '../utils/CommonConstant';

export function getLatestData() {
  return new Promise((resolve, reject) => {
    wx.request({
      url: CommonConstant.SHOW_SHADOW,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'x-auth-token': CommonConstant.token
      },
      dataType: 'json',
      success(res) {
        if (res.statusCode === 200) {
          const result = JSON.stringify(res.data);
          console.log("设备最新数据=", result);
          resolve(result);
        } else {
          reject(new Error("请求失败"));
        }
      },
      fail(err) {
        console.error("网络请求失败", err);
        reject(new Error("网络请求失败"));
      }
    });
  });
}
//控制设备
// api/device.js
export function controlDevice(params) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: CommonConstant.CONTROL_DEVICE_SYNC,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'x-auth-token': CommonConstant.token
      },
      data: params,
      dataType: 'json',
      success(res) {
        if (res.statusCode === 200 && JSON.stringify(res.data).includes("command_id")) {
          console.log("控制设备=", "控制成功");
          resolve("控制成功");
        } else {
          reject(new Error("操作失败"));
        }
      },
      fail(err) {
        console.error("网络请求失败", err);
        reject(new Error("网络请求失败"));
      }
    });
  });
}